﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MySql.Data.MySqlClient;
using DateBaseConnectionPool;

namespace TestMySqlConnetPoll
{
    [Serializable]
    public class HistroyAlarmObj
    {
        public HistroyAlarmObj()
        {
            alarmObj = new ObjAlaram();
        }

        public int AlarmLevel_int { get; set; }
        public string u_time { get; set; }          //时间，报警开始时间
        public string AlarmLevel { get; set; }      //报警级别
        public string AlarmType { get; set; }       //报警类型 技术标准规定的报警子类型
        public string ex_AlarmType { get; set; }    //扩展报警类型
        public string statue { get; set; }          //报警状态
        public string tcFlag { get; set; }          //天窗修状态
        public string dev_type { get; set; }        //设备类型，开关量当一种特殊的模拟量类型
        public string AnalogName { get; set; }
        public string e_time { get; set; }          //报警结束时间
        public string d_time { get; set; }          //报警延迟时间
        public string DevTypeName { get; set; }
        public string devName { get; set; }         //设备名称
        public string AlarmText { get; set; }       //报警内容
        public string ConfirmName { get; set; }     //报警确认人
        public string ConfirmText { get; set; }     //报警确认内容
        public string ConfirmTime { get; set; }     //报警确认时间

        public ObjAlaram alarmObj;
    }
    [Serializable]
    
    public class ObjAlaram
    {
        public int u_time;         //时间，报警开始时间
        public byte AlarmLevel;    //报警级别
        public byte AlarmType;     //报警类型 技术标准规定的报警子类型
        public byte ex_AlarmType;  //扩展报警类型
        public byte statue;        //报警状态
        public byte tcFlag;        //天窗修状态
        public byte dev_type;      //设备类型，开关量当一种特殊的模拟量类型
        public Int16 dev_no;       //设备序号
        public int e_time;         //报警结束时间
        public int d_time;         //报警延迟时间        
        public string devName;        
        public string AlarmText;     //报警内容        
        public string ConfirmName;    //报警确认人        
        public string ConfirmText;   //报警确认内容
        public int ConfirmTime;    //报警确认时间
    }
    public class AlarmTable
    {
        #region 外部函数定义 变量定义 报警

        public struct AlarmThreadStruct
        {
            public string TableName;
            public byte AlarmType;
            public string SelectStatement;
        }
        /// <summary>
        /// 报警列表，以报警类型做键值
        /// </summary>
        public Dictionary<byte, List<ObjAlaram>> ValueList = new Dictionary<byte, List<ObjAlaram>>();
        public List<int> TimeList = new List<int>();
        public bool Ready_AlarmValueList = false;
        public bool Ready_timeList = false;
        public int ErrorFlag = 0;

        //public void Read_ValueList(DateTime stime,DateTime etime,string AlarmType,int AlarmLevel,string DevType,string DevName)
        public void Read_ValueList(DateTime stime, DateTime etime, List<string> AlarmType, List<int> AlarmLevel, string DevType, string DevName)
        {
            StringBuilder s = new StringBuilder();
            if (etime == DateTime.MinValue)
            {
                stime = new DateTime(stime.Year, stime.Month, stime.Day, 0, 0, 0);
                etime = new DateTime(stime.Year, stime.Month, stime.Day, 23, 59, 59);
            }
            if (stime.DayOfYear == etime.DayOfYear)  //同一天
            {
                s.Append(string.Format("y_day = {0}", stime.DayOfYear));
            }
            else
            {
                s.Append(string.Format("(y_day = {0} ", stime.DayOfYear));
                TimeSpan t3 = etime.Subtract(stime);
                for (int i = 1; i <= t3.Days; i++)
                {
                    s.Append(string.Format(" or y_day = {0}", stime.AddDays(i).DayOfYear));
                }
                s.Append(")");
            }

                int t1 = MySql.DateTimeToTime_t(stime);
                int t2 = MySql.DateTimeToTime_t(etime);
                s.Append(string.Format(" and  u_time >= {0} and u_time <= {1}", t1, t2));
            
            if (AlarmType.Count > 0)
            {
                s.Append(string.Format(" and ("));
                for (int i = 0; i < AlarmType.Count; i++)
                {
                    int type = c_Device.GetAlarmTypeCode(AlarmType[i]);
                    if (type != -1)
                    {
                        if (i != 0) s.Append(string.Format(" or "));
                        s.Append(string.Format(" alarmtype = {0}", type));
                    }
                }
                s.Append(")");
            }
            if (AlarmLevel.Count > 0)
            {
                s.Append(string.Format(" and ("));
                for (int i = 0; i < AlarmLevel.Count; i++)
                {
                    if (i != 0) s.Append(string.Format(" or "));
                    s.Append(string.Format(" alarmLevel = {0}", AlarmLevel[i]));
                }
                s.Append(")");
            }
            if (DevType != "" && DevName != "")     //该设备所有的属性报警提出来.
            {
                s.Append(" and ");
                List<AnalogObj> li = c_Device.GetDevAttributeList(DevType, DevName);
                int oldtype = -1;
                foreach (AnalogObj key in li)
                {
                    int type = 0;
                    if (key.type == AnalogCodeType.None) type = 0xff;   //开关量作为类型
                    else type = (int)key.type;
                    if (oldtype != type)
                    {
                        if (oldtype == -1) s.Append(string.Format(" dev_type = {0}", type)); //第一次不加or
                        else s.Append(string.Format(" or dev_type = {0}", type));
                        oldtype = type;
                    }
                }
                s.Append(" and ");
                int oldno = -1;
                foreach (AnalogObj key in li)
                {
                    if (oldno == -1) s.Append(string.Format(" dev_no = {0}", key.devNo));
                    else s.Append(string.Format(" or dev_no = {0}", key.devNo));
                    oldno = key.devNo;
                }
            }
            Read_ValueList(s.ToString());
        }

        public void Read_ValueList(string SelectStatement)
        {
            ErrorFlag = 0;
            ValueList.Clear();
            AlarmThreadStruct obj = new AlarmThreadStruct();
            Ready_AlarmValueList = false;
            obj.TableName = "AlarmTable";
            obj.SelectStatement = SelectStatement;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadAlarmValueList), obj);
        }
        /// <summary>
        /// 读报警时间列表，没有按照每天区分
        /// </summary>
        /// <param name="AlarmType"></param>
        public void ReadTimeList(byte AlarmType)
        {
            ErrorFlag = 0;
            Ready_timeList = false;
            TimeList.Clear();
            AlarmThreadStruct obj = new AlarmThreadStruct();

            obj.TableName = "AlarmTable";
            //obj.SelectStatement = SelectStatement;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadReadTimeList), obj);
        }

        #endregion

        private Mutex keyMutex = new Mutex();
        private static int keykey = 0;

        #region 报警

        private void ThreadReadTimeList(object o)
        {
            AlarmThreadStruct obj = (AlarmThreadStruct)o;

            string TableName = obj.TableName;
            byte type = obj.AlarmType;

            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                       
                if (con != null)
                {
                    StringBuilder s = new StringBuilder();
                    s.Append(string.Format("select u_time from {0} where alarmtype = {1} order by u_time", TableName, type));
                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(s.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            int u_time = read.GetInt32(read.GetOrdinal("u_time"));
                            TimeList.Add(u_time);
                        }
                        read.Close();
                        Ready_timeList = true;
                    }
                    catch
                    {
                        ErrorFlag = 2;
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 3;
                    }
                }
                else
                {
                    ErrorFlag = 4;
                }
            }
            else ErrorFlag = 5;
        }

        public void InsertData_AlarmTable(List<ObjAlaram> objlist)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadInsert), objlist);
        }

        /// <summary>
        /// 插入报警表，如果是状态更新，需要删除同一个报警，
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public void ThreadInsert(object o)
        {
            List<ObjAlaram> objlist = o as List<ObjAlaram>;
            string TableName = "AlarmTable";
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                        

                if (con != null)
                {
                    foreach (ObjAlaram obj in objlist)
                    {
                        StringBuilder DelStatement = new StringBuilder();
                        DelStatement.Append(string.Format("delete from {0} where u_time = {1} and alarmtype = {2} and ex_type = {3} ", TableName, obj.u_time, obj.AlarmType, obj.ex_AlarmType));
                        DelStatement.Append(string.Format(" and dev_type = {0} and dev_no = {1}", obj.dev_type, obj.dev_no));

                        MySqlCommand delcommand = new MySqlCommand(DelStatement.ToString(), con);
                        delcommand.ExecuteNonQuery();
                    }
                    StringBuilder InsertStatement = new StringBuilder();

                    InsertStatement.Append(string.Format("insert into {0}(y_day,u_time,alarmLevel,alarmtype,ex_type,dev_type,dev_no", TableName));
                    InsertStatement.Append(",statue,tc_flag,e_time,d_time,AlarmText,devName,confirmName,confirmTime,confirmText)");

                    InsertStatement.Append("values");

                    for (int i = 0; i < objlist.Count; i++)
                    {
                        if (i != 0)
                            InsertStatement.Append(",");
                        InsertStatement.Append(string.Format("(?y_day{0},?u_time{0},?alarmLevel{0},?alarmtype{0},?ex_type{0},?dev_type{0},?dev_no{0}", i));
                        InsertStatement.Append(string.Format(",?statue{0},?tc_flag{0},?e_time{0},?d_time{0},?AlarmText{0},?devName{0},?confirmName{0},?confirmTime{0},?confirmText{0})", i));
                    }
                    MySqlCommand InsertCommand = new MySqlCommand(InsertStatement.ToString(), con);
                    for (int i = 0; i < objlist.Count; i++)
                    {
                        ObjAlaram obj = objlist[i];
                        int day = MySql.Time_tToDateTime(obj.u_time).DayOfYear;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?y_day{0}", i), MySqlDbType.Int32)).Value = day;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?u_time{0}", i), MySqlDbType.Int32)).Value = obj.u_time;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?alarmLevel{0}", i), MySqlDbType.UByte)).Value = obj.AlarmLevel;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?alarmtype{0}", i), MySqlDbType.UByte)).Value = obj.AlarmType;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?ex_type{0}", i), MySqlDbType.UByte)).Value = obj.ex_AlarmType;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?dev_type{0}", i), MySqlDbType.UByte)).Value = obj.dev_type;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?dev_no{0}", i), MySqlDbType.Int16)).Value = obj.dev_no;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?statue{0}", i), MySqlDbType.UByte)).Value = obj.statue;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?tc_flag{0}", i), MySqlDbType.UByte)).Value = obj.tcFlag;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?e_time{0}", i), MySqlDbType.Int32)).Value = obj.e_time;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?d_time{0}", i), MySqlDbType.Int32)).Value = obj.d_time;

                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?AlarmText{0}", i), MySqlDbType.VarChar)).Value = obj.AlarmText;


                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?devName{0}", i), MySqlDbType.VarChar)).Value = obj.devName;


                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmName{0}", i), MySqlDbType.VarChar)).Value = obj.ConfirmName;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmTime{0}", i), MySqlDbType.Int32)).Value = obj.ConfirmTime;

                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmText{0}", i), MySqlDbType.VarChar)).Value = obj.ConfirmText;
                    }                    
                    try
                    {
                        int k = InsertCommand.ExecuteNonQuery();
                        if (k == objlist.Count) ErrorFlag = 0;        //写入成功
                        else ErrorFlag = 2;              //写入失败
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                        ErrorFlag = 3;       //写入失败
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                    }
                }
            }
        }

        /// <summary>
        /// 报警查询，报警的查询条件可组合的太多，在本函数内没办法一一列举，只能在外面写好查询语句
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="SelectStatement"></param>
        /// <returns></returns>
        private void ThreadReadAlarmValueList(object o)
        {
            AlarmThreadStruct obj = (AlarmThreadStruct)o;

            string TableName = obj.TableName;
            string SelectStatement = obj.SelectStatement;
            ValueList.Clear();

            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString(); 
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                        
                if (con != null)
                {
                    StringBuilder s = new StringBuilder();

                    s.Append(string.Format("select u_time,alarmLevel,alarmtype,ex_type,dev_type,dev_no,statue,tc_flag"));
                    s.Append(string.Format(",e_time,d_time,devName,AlarmText,confirmName,confirmTime,confirmText "));
                    s.Append(string.Format(" from {0} where {1} order by u_time", TableName, SelectStatement));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(s.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            ObjAlaram t = new ObjAlaram();
                            t.u_time = read.GetInt32(read.GetOrdinal("u_time"));
                            t.AlarmLevel = read.GetByte(read.GetOrdinal("alarmLevel"));
                            t.AlarmType = read.GetByte(read.GetOrdinal("alarmtype"));
                            t.ex_AlarmType = read.GetByte(read.GetOrdinal("ex_type"));
                            t.dev_type = read.GetByte(read.GetOrdinal("dev_type"));
                            t.dev_no = read.GetInt16(read.GetOrdinal("dev_no"));
                            t.statue = read.GetByte(read.GetOrdinal("statue"));
                            t.tcFlag = read.GetByte(read.GetOrdinal("tc_flag"));
                            t.e_time = read.GetInt32(read.GetOrdinal("e_time"));
                            t.d_time = read.GetInt32(read.GetOrdinal("d_time"));

                            if (!read.IsDBNull(read.GetOrdinal("devName")))
                            {
                                t.devName = read.GetString(read.GetOrdinal("devName")); //设备名称
                            }
                            if (!read.IsDBNull(read.GetOrdinal("AlarmText")))
                            {
                                t.AlarmText = read.GetString(read.GetOrdinal("AlarmText"));
                            }
                            if (!read.IsDBNull(read.GetOrdinal("confirmName")))
                            {
                                t.ConfirmName = read.GetString(read.GetOrdinal("confirmName"));
                            }
                            t.ConfirmTime = read.GetInt32(read.GetOrdinal("confirmTime"));
                            if (!read.IsDBNull(read.GetOrdinal("confirmText")))
                            {
                                t.ConfirmText = read.GetString(read.GetOrdinal("confirmText"));
                            }

                            if (ValueList.ContainsKey(t.AlarmType))
                            {                                
                                ValueList[t.AlarmType].Add(t);
                            }
                            else
                            {
                                List<ObjAlaram> l = new List<ObjAlaram>();
                                l.Add(t);
                                ValueList.Add(t.AlarmType, l);
                            }
                        }
                        read.Close();
                        Ready_AlarmValueList = true;
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 2;
                    }

                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 3;
                    }
                }
                else ErrorFlag = 6;
            }
            else ErrorFlag = 7;
        }
        #endregion
    }

    public class rtAlarmTable
    {        
        /// <summary>
        /// 报警列表，以报警类型做键值
        /// </summary>
        public Dictionary<byte, List<ObjAlaram>> ValueList = new Dictionary<byte, List<ObjAlaram>>();        
        public bool Ready_Read = false;        
        public int ErrorFlag = 0;
        private Mutex keyMutex = new Mutex();
        static private int keykey = 0;

        public void Delete(List<ObjAlaram> li)
        {
            ThreadPool.QueueUserWorkItem(ThreadDelete, li);
        }
        public void  ThreadDelete(object o)
        {
            List<ObjAlaram> li = o as List<ObjAlaram>;
            string TableName = "rtAlarmTable";
            bool rt = true;
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + (MySql.key++).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    rt = false;
                }
                if (con != null)
                {
                    foreach (ObjAlaram obj in li)
                    {
                        StringBuilder DelStatement = new StringBuilder();
                        DelStatement.Append(string.Format("delete from {0} where u_time = {1} and alarmtype = {2} and ex_type = {3} ", TableName, obj.u_time, obj.AlarmType, obj.ex_AlarmType));
                        DelStatement.Append(string.Format(" and dev_type = {0} and dev_no = {1}", obj.dev_type, obj.dev_no));
                        try
                        {
                            MySqlCommand delcommand = new MySqlCommand(DelStatement.ToString(), con);
                            delcommand.ExecuteNonQuery();
                        }
                        catch (MySqlException e)
                        {
                            rt = false;
                        }
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        rt = false;
                    }
                }
                else rt = false;
            }
            else rt = false;
        }

        public void Insert(List<ObjAlaram> li)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadInsert), li);
        }

        private void ThreadInsert(object o)
        {
            List<ObjAlaram> li = o as List<ObjAlaram>;
            bool tmpFlag = false;
            string TableName = "rtAlarmTable";
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    tmpFlag = false;
                }
                        
                if (con != null)
                {
                    StringBuilder InsertStatement = new StringBuilder();

                    InsertStatement.Append(string.Format("insert into {0}(y_day,u_time,alarmLevel,alarmtype,ex_type,dev_type,dev_no", TableName));
                    InsertStatement.Append(",statue,tc_flag,e_time,d_time,AlarmText,devName,confirmName,confirmTime,confirmText)");

                    InsertStatement.Append("values");

                    for (int i = 0; i < li.Count; i++)
                    {
                        if (i != 0) InsertStatement.Append(",");
                        InsertStatement.Append(string.Format("(?y_day{0},?u_time{0},?alarmLevel{0},?alarmtype{0},?ex_type{0},?dev_type{0},?dev_no{0}", i));
                        InsertStatement.Append(string.Format(",?statue{0},?tc_flag{0},?e_time{0},?d_time{0},?AlarmText{0},?devName{0},?confirmName{0},?confirmTime{0},?confirmText{0})", i));
                    }
                    MySqlCommand InsertCommand = new MySqlCommand(InsertStatement.ToString(), con);
                    for (int i = 0; i < li.Count; i++)
                    {
                        ObjAlaram obj = li[i];
                        int day = MySql.Time_tToDateTime(obj.u_time).DayOfYear;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?y_day{0}", i), MySqlDbType.Int32)).Value = day;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?u_time{0}", i), MySqlDbType.Int32)).Value = obj.u_time;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?alarmLevel{0}", i), MySqlDbType.UByte)).Value = obj.AlarmLevel;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?alarmtype{0}", i), MySqlDbType.UByte)).Value = obj.AlarmType;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?ex_type{0}", i), MySqlDbType.UByte)).Value = obj.ex_AlarmType;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?dev_type{0}", i), MySqlDbType.UByte)).Value = obj.dev_type;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?dev_no{0}", i), MySqlDbType.Int16)).Value = obj.dev_no;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?statue{0}", i), MySqlDbType.UByte)).Value = obj.statue;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?tc_flag{0}", i), MySqlDbType.UByte)).Value = obj.tcFlag;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?e_time{0}", i), MySqlDbType.Int32)).Value = obj.e_time;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?d_time{0}", i), MySqlDbType.Int32)).Value = obj.d_time;

                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?AlarmText{0}", i), MySqlDbType.VarChar)).Value = obj.AlarmText;


                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?devName{0}", i), MySqlDbType.VarChar)).Value = obj.devName;


                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmName{0}", i), MySqlDbType.VarChar)).Value = obj.ConfirmName;
                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmTime{0}", i), MySqlDbType.Int32)).Value = obj.ConfirmTime;

                        InsertCommand.Parameters.Add(new MySqlParameter(string.Format("?confirmText{0}", i), MySqlDbType.VarChar)).Value = obj.ConfirmText;
                    }
                    try
                    {
                        int k = InsertCommand.ExecuteNonQuery();
                        if (k == li.Count) tmpFlag = true;        //写入成功
                        else tmpFlag = false;              //写入失败
                    }
                    catch (MySqlException e)
                    {
                        //写异常日记
                        tmpFlag = false;       //写入失败
                    }
                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        tmpFlag = false;       //写入失败
                    }
                }
            }
        }

        public void Read()
        {
            ErrorFlag = 0;
            ValueList.Clear();            
            Ready_Read = false;
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadRead), null);
        }

        private void ThreadRead(object o)
        {
            string TableName = "rtAlarmTable";
            ValueList.Clear();
            if (MySql.c != null && MySql.c.State == PoolState.Run)
            {
                MySqlConnection con = new MySqlConnection();
                string key = TableName + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Interlocked.Increment(ref keykey).ToString();
                try
                {
                    con = (MySqlConnection)MySql.c.GetConnectionFormPool(key);
                }
                catch (MySqlException ex)
                {
                    //写异常日志
                    ErrorFlag = 1;
                }
                        
                if (con != null)
                {
                    StringBuilder s = new StringBuilder();

                    s.Append(string.Format("select u_time,alarmLevel,alarmtype,ex_type,dev_type,dev_no,statue,tc_flag"));
                    s.Append(string.Format(",e_time,d_time,devName,AlarmText,confirmName,confirmTime,confirmText "));
                    s.Append(string.Format(" from {0} order by u_time", TableName));

                    try
                    {
                        MySqlCommand selectCommand = new MySqlCommand(s.ToString(), con);
                        selectCommand.CommandTimeout = 120;   //120s操作超时

                        MySqlDataReader read = selectCommand.ExecuteReader();
                        while (read.Read())
                        {
                            ObjAlaram t = new ObjAlaram();
                            t.u_time = read.GetInt32(read.GetOrdinal("u_time"));
                            t.AlarmLevel = read.GetByte(read.GetOrdinal("alarmLevel"));
                            t.AlarmType = read.GetByte(read.GetOrdinal("alarmtype"));
                            t.ex_AlarmType = read.GetByte(read.GetOrdinal("ex_type"));
                            t.dev_type = read.GetByte(read.GetOrdinal("dev_type"));
                            t.dev_no = read.GetInt16(read.GetOrdinal("dev_no"));
                            t.statue = read.GetByte(read.GetOrdinal("statue"));
                            t.tcFlag = read.GetByte(read.GetOrdinal("tc_flag"));
                            t.e_time = read.GetInt32(read.GetOrdinal("e_time"));
                            t.d_time = read.GetInt32(read.GetOrdinal("d_time"));

                            if (!read.IsDBNull(read.GetOrdinal("devName")))
                            {
                                t.devName = read.GetString(read.GetOrdinal("devName")); //设备名称
                            }
                            if (!read.IsDBNull(read.GetOrdinal("AlarmText")))
                            {
                                t.AlarmText = read.GetString(read.GetOrdinal("AlarmText"));
                            }
                            if (!read.IsDBNull(read.GetOrdinal("confirmName")))
                            {
                                t.ConfirmName = read.GetString(read.GetOrdinal("confirmName"));
                            }
                            t.ConfirmTime = read.GetInt32(read.GetOrdinal("confirmTime"));
                            if (!read.IsDBNull(read.GetOrdinal("confirmText")))
                            {
                                t.ConfirmText = read.GetString(read.GetOrdinal("confirmText"));
                            }

                            if (ValueList.ContainsKey(t.AlarmType))
                            {                                
                                ValueList[t.AlarmType].Add(t);
                            }
                            else
                            {
                                List<ObjAlaram> l = new List<ObjAlaram>();
                                l.Add(t);
                                ValueList.Add(t.AlarmType, l);
                            }
                        }
                        read.Close();
                        Ready_Read = true;
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 2;
                    }

                    try
                    {
                        MySql.c.DisposeConnection(key);
                    }
                    catch (MySqlException e)
                    {
                        ErrorFlag = 3;
                    }
                }
                else ErrorFlag = 6;
            }
            else ErrorFlag = 7;
        }
    }
}
